package concurrency.reentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class ReentrantLockTest3_condition {

    private static ReentrantLock room = new ReentrantLock();
    //定义两个条件
    private static Condition waitCarQueue=room.newCondition();
    private static Condition waitTrainQueue=room.newCondition();
    //定义两个标志
    private static boolean isCar=false;
    private static boolean isTrain=false;

    public static void main(String[] args) {

        //等汽车线程
        new Thread(()->{
            try {
                room.lock();
                //汽车来了没
                log.debug("汽车来了没？",isCar);
                while (!isCar){
                    //车没来，在汽车候车区等待
                    try {
                        waitCarQueue.await();
                        System.out.println(isCar);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug(isCar?"汽车来了":"汽车还没来");
            } finally {
                room.unlock();
            }
        },"等汽车线程").start();

        //等火车线程
        new Thread(()->{
            try {
                room.lock();
                //火车来了没
                log.debug("火车来了没？",isTrain);
                while (!isTrain){
                    //车没来，在火车候车区等待
                    try {
                        waitTrainQueue.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug(isTrain?"火车来了":"火车还没来");
            } finally {
                room.unlock();
            }
        },"等火车线程").start();

        try {
            Thread.sleep(1000);
            log.debug("等一秒后，汽车来了");
            new Thread(()->{
                room.lock();
                try {
                    isCar=true;
                    waitCarQueue.signal();
                } finally {
                    room.unlock();
                }
            },"汽车线程").start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            Thread.sleep(1000);
            log.debug("又等一秒后，火车来了");
            new Thread(()->{
                room.lock();
                try {
                    isTrain=true;
                    waitTrainQueue.signal();
                } finally {
                    room.unlock();
                }
            },"火车线程").start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}
